<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="24">
            <a-form-model-item label="流程定义id" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="processId" v-if="false">
              <a-input :disabled=formDisabled v-model="model.processId" placeholder="请输入流程定义id"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="processName">
              <j-popup
                :multi="false"
                :disabled=formDisabled
                v-model="model.processName"
                field="processName"
                org-fields="process_name,id"
                dest-fields="processName,processId"
                code="sys_process_report"
                @input="popupCallback"
                />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="应用部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyDepart">
              <!-- <a-input :disabled=formDisabled v-model="model.applyDepart" placeholder="请输入应用部门"  ></a-input> -->
              <j-select-depart placeholder="请选择应用部门" :disabled=formDisabled v-model="model.applyDepart" :multi="false" @change="getapplydepart" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="流程是否更新" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isUpdate">-->
<!--              <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.isUpdate" dictCode="YES_OR_NO" placeholder="请选择流程是否更新" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>
        <a-tabs defaultActiveKey="1" >
          <a-tab-pane tab="流程节点人员配置" key="1">
            <div>
              <a-row type="flex" style="margin-bottom:10px" :gutter="24">
                <a-col :span="9">节点名称</a-col>
                <a-col :span="14">执行人</a-col>
<!--                <a-col :span="5">备注</a-col>-->
              </a-row>

              <a-row :gutter="24" v-for="(item, index) in model.erpProcessConfigMainVoList" :key="index">
                <div v-if="item.taskType.includes('UserTask') || item.nodeName.includes('知会')" style="margin-bottom:20px">
                  <a-col :span="6" style="display: none">
                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.id">
                      <!-- <a-input placeholder="id" v-decorator="[item.id, {'initialValue':item.id}]" /> -->
                      <a-input placeholder="id" v-model="item.id" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="6"  style="display: none">
                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.execDepart">
                      <!-- <j-select-depart placeholder="请选择执行部门" :disabled=formDisabled v-decorator="[item.execDepart, {'initialValue':item.execDepart}]" :multi="false"  /> -->
                      <a-input placeholder="请选择执行部门" disabled v-model="item.execDepart"    />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="6" style="display: none">
                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.processNodeCode">
                      <!-- <a-input placeholder="id" v-decorator="[item.id, {'initialValue':item.id}]" /> -->
                      <a-input placeholder="processNodeCode" v-model="item.processNodeCode" />
                    </a-form-model-item>
                  </a-col>
<!--                  <a-col :span="7">-->
<!--                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.nodeId">-->
<!--                      &lt;!&ndash; <j-dict-select-tag type="list" placeholder="节点名称"  v-decorator="[item.nodeId,{'initialValue':item.nodeId}]"   dictCode="ext_act_process_node,process_node_name,id"  /> &ndash;&gt;-->
<!--                      <j-dict-select-tag type="list" placeholder="节点名称" disabled   v-model="item.nodeId"   dictCode="ext_act_process_node,process_node_name,id"  />-->
<!--                    </a-form-model-item>-->
<!--                  </a-col>-->
                  <a-col :span="9"  style="display: none">
                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.nodeId">
                      <a-input placeholder="节点名称"    v-model="item.nodeId" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="9">
                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.nodeName">
                      <!-- <j-dict-select-tag type="list" placeholder="节点名称"  v-decorator="[item.nodeId,{'initialValue':item.nodeId}]"   dictCode="ext_act_process_node,process_node_name,id"  /> -->
                      <a-input placeholder="节点名称"  disabled v-model="item.nodeName" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="14" v-if="item.isConfigExpression === '0'  || item.notifyIsCustom === '1'">
                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.execUser">
<!--                      <j-select-user-by-dep v-model="item.execUser" disabled :multi="true"></j-select-user-by-dep>-->
                      <a-input disabled  value="当前节点无需配置" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="14" v-else>
                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.execUser">
                      <j-select-user-by-dep v-model="item.execUser" :disabled="formDisabled" :multi="true" ></j-select-user-by-dep>
                    </a-form-model-item>
                  </a-col>
<!--                  <a-col :span="5"  v-if="item.isConfigExpression=='0' ">-->
<!--                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.remark">-->
<!--                      <a-input placeholder="备注" value="当前节点无需配置" disabled />-->
<!--                    </a-form-model-item>-->
<!--                  </a-col>-->
<!--                  <a-col :span="5" v-else>-->
<!--                    <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" :prop="item.remark">-->
<!--                      <a-input placeholder="备注" v-model="item.remark" :disabled="formDisabled" />-->
<!--                    </a-form-model-item>-->
<!--                  </a-col>-->
                </div>
              </a-row>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  // import { validateDuplicateValue } from '@/utils/util'
  import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  // import pick from 'lodash.pick';
  // import moment from 'moment';
  export default {
    name: 'erpProcessConfigForm',
    components: {
      SelectPersonInput,
      JSelectUserByDep
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch:{
      model:{
        handler(val,old){
          //加载当前部门的分管领导
          this.setDeputyMinisters(val.applyDepart)
        }
      }
    },
    data () {
      return {
        model:{
          erpProcessConfigMainVoList: []
        },
        //当前选择部门对应的分管领导
        deputyMinisters: null,
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          applyDepart: [
            { required: true, message: '请选择部门!' }
          ],
        },
        url: {
          add: "/api/erp/process/erpProcessConfig/add",
          edit: "/api/erp/process/erpProcessConfig/edit",
          save: '/api/erp/process/erpProcessConfig/saveOrUpdateProcess',
          queryById: "/api/erp/process/erpProcessConfig/queryProcessById",
          queryProcessMainListById: '/api/erp/process/erpProcessConfigMain/queryProcessMainListById',
          quertyProcessNodeListById: '/api/erpmng/act/process/extActProcessNode/queryProcessNodeListById',
          queryDeputyMinistersByDepartId: '/api/erpmng/sys/sysDepart/queryDeputyMinistersByDepartId'
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      // addRowCustom () {
      //   this.erpProcessConfigMainVoList.push({});
      //   this.$forceUpdate();
      // },
      // delRowCustom (index) {
      //   console.log(index)
      //   // let all = this.form.getFieldsValue()
      //   // all['erpProcessConfigMainVoList'].splice(index,1);
      //   // this.form.setFieldsValue(all)
      //   this.erpProcessConfigMainVoList.splice(index,1);
      //   this.$forceUpdate();
      // },
      getapplydepart(value){
        this.model.erpProcessConfigMainVoList.forEach(val => {
          val.execDepart = value
        })
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.model.erpProcessConfigMainVoList = [];
        //初始化明细表数据
        if(this.model.id){
          let params = {id: this.model.id}
          // //初始化流程配置详情
          // getAction(this.url.queryProcessMainListById,params).then((res)=>{
          //   if(res.success){
          //     this.$set(this.model,'erpProcessConfigMainVoList',res.result)
          //     this.$forceUpdate()
          //   }
          // })
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.model = Object.assign({}, res.result);
            }
          })
        }
        this.visible = true;
      },
      submitForm () {
        const that = this;
        console.log('that.model', that.model)
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            // let value = that.model.erpProcessConfigMainVoList.filter(val => !val.execUser || !val.nodeId)
        /*     let value = that.model.erpProcessConfigMainVoList.filter(val => !val.nodeId)
            console.log(value);
            if(value.length > 0){
              this.$message.warning('请选择执行人或节点')
              that.confirmLoading = false;
              return
            } */
            let flag = false;
            this.model.erpProcessConfigMainVoList.forEach(val => {
              console.log('val', val)
              if (val.taskType.includes('UserTask') || val.nodeName.includes('知会')) {
                if (val.isConfigExpression !== '0' && val.notifyIsCustom !== '1') {
                  if (!val.execUser) {
                    this.$message.warning('请完善执行人')
                    that.confirmLoading = false;
                    flag = true
                    return false;
                  }
                }
              }
            })
            if (flag) {
              return
            }
            // let httpurl = '';
            const method = 'post';
            // if(!this.model.id){
            //   httpurl+=this.url.add;
            //   method = 'post';
            // }else{
            //   httpurl+=this.url.edit;
            //    method = 'put';
            // }
            httpAction(this.url.save,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      popupCallback(value,row,obj){
        this.model.erpProcessConfigMainVoList = [];
        let data = []
        console.log('-----------------row',value, row)
        this.$set(this.model,'processId',obj.id)
        this.$set(this.model,'processName',obj.process_name)
        // this.model = Object.assign(this.model, row);
        // 查询要业务信息档案
        getAction(this.url.quertyProcessNodeListById, { id: obj.id }).then(res => {
          if(res.success){
            res.result.forEach((res) => {
              // 添加写死条件原因(目前就车辆申请要求自动填写分管领导，其他的流程统一需要把第二个条件去掉即可)
              if(this.model.applyDepart && res.processId!='1551852856610439169'){
                data.push({ nodeId: res.id, nodeName: res.processNodeName,processNodeCode: res.processNodeCode,execDepart: this.model.applyDepart,taskType: res.taskType,isMultAssignee: res.isMultAssignee,isConfigExpression: res.isConfigExpression, notifyIsCustom: res.notifyIsCustom, isSelectDisabled: res.isSelectDisabled })
              } else {
                data.push({ nodeId: res.id, nodeName: res.processNodeName,processNodeCode: res.processNodeCode,taskType: res.taskType,isMultAssignee: res.isMultAssignee,isConfigExpression: res.isConfigExpression, notifyIsCustom: res.notifyIsCustom, isSelectDisabled: res.isSelectDisabled})
              }
            })
            this.$set(this.model,'erpProcessConfigMainVoList',data)
            this.$forceUpdate()
            console.log('this.model.erpProcessConfigMainVoList', this.model.erpProcessConfigMainVoList)
          }
        })
      },
      // 动态获取部门分管领导
      setDeputyMinisters(applyDepartId){
        console.log("applyDepartId=",applyDepartId)
        if(!applyDepartId){
          this.deputyMinisters = null;
          return;
        }
        // 根据当前应用部门获取分管领导
        getAction(this.url.queryDeputyMinistersByDepartId,{id:applyDepartId}).then(res=>{
          if(res.success){
            this.deputyMinisters = res.result;
          }
          // 设置列表中的值
          if(this.model.erpProcessConfigMainVoList){
            this.model.erpProcessConfigMainVoList.forEach(node=>{
              // 当前节点名称为分管领导就自动填充(写死流程id原因：目前就车辆申请要求自动填写分管领导，其他的流程统一需要把第一个条件去掉即可)
              if(this.model.processId == '1551852856610439169' && node.nodeName && node.nodeName == '分管领导'){
                node.execUser = this.deputyMinisters;
                this.$forceUpdate()
              }
            })
          }
        }).catch(e=>{
          console.log(e)
        })
      }
    }
  }
</script>
